<?php
/**
 * Author: Hancock
 * Email: 84622365@qq.com
 * Date: 3/23/2016
 * Des: 爬虫
 */
defined('INHkMvc') or exit('Access Invalid!');
include_once ROOT_PATH . 'inc/phpQuery/phpQuery.php';

class SpController extends Controller
{
    public function indexAct()
    {
        exit("bless me");
    }

    public function getGoodInfoAct()
    {
        $num_iid = trim($_POST['num_iid']);
        $url = 'https://item.taobao.com/item.htm?id=' . $num_iid;
        $html = file_get_contents($url);
        $html = mb_convert_encoding($html, 'utf-8', 'GBK');
        $q = phpQuery::newDocumentHTML($html);

        //获取商品价格
        $match = '/\{"price"\:"[a-z0-9\.]+"[^\}]+\}(,|\})/i';
        preg_match_all($match, $html, $matches);

        $prices = $matches[0];
        foreach ($prices as &$p) {
            $p = str_replace("}}", "}", $p);
            $p = str_replace("},", "}", $p);
            $p = json_decode($p, 1)['price'];
        }

        asort($prices);
        $price = array_shift($prices);

        //获取产品名称
        $title = $q["title"]->html();

        //获取产品主图,默认细节图第一张

        //获取产品细节图
        $thumbs = [];
        $length = ($q["ul.tb-thumb img"]->length());
        for ($i = 0; $i < $length; $i++) {
            $thumb = "http:" . $q["ul.tb-thumb img:eq($i)"]->attr('data-src');
            $thumb = trim($thumb != "http:") ? $thumb : "http:" . $q["ul.tb-thumb img:eq($i)"]->attr('src');
            $thumbs[] = str_replace("50x50", "800x800", $thumb);
        }

        //获取产品详情
        $match = '/(\/\/(?:dsc|desc)\.(?:taobaocdn|alicdn)\.com[^\"]*)/i';
        preg_match_all($match, $html, $matches);
        if (strstr($matches[0][0], "lazyload")) {
            $match = '/(\/\/(?:dsc|desc)\.(?:taobaocdn|alicdn)\.com[^\']*)/i';
            preg_match_all($match, $html, $matches);
        }
        $urls = $matches[0];
        $desc = "";
        foreach ($urls as $url) {
            $desc .= trim(str_replace("var desc=", "", file_get_contents("http:" . $url)), "'");
            if (strlen($desc) > 0 && $desc != null) {
                break;
            }
        }

        // var_dump($title);
        // var_dump($thumbs);
        // var_dump($desc);
        ajaxReturn(200, ['title' => $title, 'thumb' => $thumbs, 'price' => $price]);
    }


}
